from contextlib import asynccontextmanager
from venv import logger
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from app.api import GaiController, AiController
from app.core.Scheduler import scheduler
from app.db.DBConfig import engine, Base



@asynccontextmanager
async def lifespan(app: FastAPI):
    scheduler.start()
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield
    scheduler.shutdown()

def create_app() -> FastAPI:
    app = FastAPI(
        title="最快捷的软著申请助手",
        version="0.0.1",
        description="轻轻松松申请软著",
        lifespan=lifespan,  # 绑定生命周期管理器
        docs_url="/docs",
        root_path="/api"
    )
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 前端域名列表
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.get("/", tags=["Root"])
    async def read_root():
        return {"message": f"欢迎使用{app.title}!"}
    app.include_router(GaiController.router)
    app.include_router(AiController.router)
    return app

app = create_app()
if __name__ == "__main__":
    logger.info("Web 模式启动...")
    port = 6678
    reload = False  # 开启热更新
    host = "0.0.0.0"
    uvicorn.run(app, host=host, port=port, reload=reload, log_level="debug")